import { ref, computed } from 'vue'
import useBaseDialog from './useBaseDialog' // 基础弹窗hook
import { ElMessage } from 'element-plus'
export default function({
  createApi,
  editApi,
  defaultForm,
  emit
}) {
  const isEditDialog = ref(false) // 修改弹窗
  const ruleForm = ref({...defaultForm}) // 表单内容
  const ruleFormRef = ref(null) // 表单ref
  const title = computed(() => {
    return isEditDialog.value ? '编辑' : '新增'
  })

  const {
    dialogVisible,// 窗口显示隐藏
    open: openDialog, // 打开方法
    close: closeDialog // 关闭方法
  } = useBaseDialog()

  /**
     * 打开弹窗
     * @defaultData 携带的默认数据
     * @isEdit 是否为修改
     */
  const open = (defaultData = null, isEdit = false) => {
    if (defaultData) {
      ruleForm.value = { // 默认数据填充
        ...defaultForm,
        ...defaultData
      }
    }
    isEditDialog.value = isEdit // 窗口模式设为edit
    openDialog()
  }

  const close = () => {
    closeDialog()
    ruleForm.value = { ...defaultForm }
    isEditDialog.value = false // 窗口模式设为create
  }

  const createFn = async() => {
    const res = await createApi(ruleForm.value)
    if (res.status === 200 || res.status === 201) {
      ElMessage.success('新增成功')
      emit('update-list')
      close()
    }
  }

  const editFn = async() => {
    const res = await editApi(ruleForm.value.id, ruleForm.value)
    if (res.status === 200 || res.status === 201) {
      ElMessage.success('修改成功')
      emit('update-list')
      close()
    }
  }

  const submit = () => {
    ruleFormRef.value.validate((valid) => {
      if (valid) {
        if (!isEditDialog.value) {
          console.log('222')
          createFn()
        } else {
          console.log('111')
          editFn()
        }
      } else {
        console.log('error submit!!')
        return false
      }
    })
  }

  return {
    dialogVisible,
    isEditDialog,
    title,
    ruleForm,
    ruleFormRef,
    open,
    close,
    submit
  }
}